package com.ms.p2p.controller.admin;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.excel.ExcelData;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.loan.Loan;
import com.ms.p2p.entity.loan.LoanCategory;
import com.ms.p2p.entity.loan.LoanImg;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.enums.LoanRepayStyle;
import com.ms.p2p.enums.LoanType;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.TokenValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.DictionaryProvider;
import com.ms.p2p.provider.LoanCategoryProvider;
import com.ms.p2p.provider.LoanProvider;
import com.ms.p2p.provider.LoanTenderRecordProvider;
import com.ms.p2p.utils.AmountUtil;
import com.ms.p2p.utils.JsonDataGridHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 借款标管理
 */
@Controller("AdminLoanController")
@RequestMapping("/admin/borrow")
public class AdminLoanController extends AdminBaseController {

    @Reference
    private LoanProvider loanProvider;
    @Reference
    private LoanTenderRecordProvider loanTenderRecordProvider;
    @Reference
    private LoanCategoryProvider loanCategoryProvider;

    @Reference
    private DictionaryProvider dictionaryProvider;

    /**
     * 截标
     */
    @RequestMapping(value = {"/cut"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Message over(HttpServletRequest request, HttpSession session) {
        Loan loan = loanProvider.findById(request.getParameter("borrowId"));
        if (loan.getStatus() != 3) {
            throw new NoticeException("截标失败，状态已经修改");

        } else {
            if (loan.getAmount_invested().compareTo(BigDecimal.ZERO) == 0) {
                throw new NoticeException("截标失败，必须有人投资过这个标");

            }

            loan.setAccount(loan.getAmount_invested());
            int i = loanProvider.overBorrow(loan);

            if (i == 1) {
                return Message.success("截标成功，请进行满标审核");

            } else {
                throw new NoticeException("截标失败，失败");

            }
        }

    }
    @RequestMapping(value = {"/queryData"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public PageBean queryData(HttpServletRequest request, HttpSession session
            , @RequestParam(value = "userId", required = false) Integer userId,
                              @RequestParam(value = "memberName", required = false) String memberName,
                              @RequestParam(value = "loanCategory", required = false) Integer loanCategory,
                              @RequestParam(value = "loanId", required = false) String loanId,
                              @RequestParam(value = "status", required = false) Integer status,
                              @RequestParam(value = "begin_date", required = false) String begin_date,
                              @RequestParam(value = "end_date", required = false) String end_date,
                              PageBean page
    ) {

        page.setTotalCount(loanProvider.findCount(loanId, memberName, userId, loanCategory, status, null, null, null, null, null, null, null, begin_date, end_date));
        page.setList(loanProvider.findPager(loanId, memberName, userId, loanCategory, status, null, null, null, null, null, null, null, begin_date, end_date, page));

        return JsonDataGridHelper.createJSONData(page);
    }
    /**
     * 查询借款标（根据条件）
     */
    @RequestMapping({"/borrowList"})
    public String borrwwList(HttpServletRequest request, HttpSession session, @RequestParam(value = "userId", required = false) Integer userId,
                             @RequestParam(value = "memberName", required = false) String memberName,
                             @RequestParam(value = "loanCategory", required = false) Integer loanCategory,
                             @RequestParam(value = "loanId", required = false) String loanId,
                             @RequestParam(value = "status", required = false) Integer status,
                             @RequestParam(value = "begin_date", required = false) String begin_date,
                             @RequestParam(value = "end_date", required = false) String end_date,
                             @RequestParam(value = "currentPage", required = false) String currentPage
    ) {
        String returnStr = "admin/borrow/verify/apply/list";
        if (status == -5) {
            returnStr = "admin/borrow/status/failed/list";
        }
        if (status == 2) {
            returnStr = "admin/borrow/status/will/list";
        }
        if (status == 0) {
            returnStr = "admin/borrow/verify/apply/list";
        }
        if (status == 3) {
            returnStr = "admin/borrow/status/loaning/list";
        }
        if (status == 4) {
            returnStr = "admin/borrow/verify/review/list";
        }

        if (status == 5) {
            returnStr = "admin/borrow/status/repaying/list";
        }
        if (status == 6) {
            returnStr = "admin/borrow/status/finish/list";
        }
        return returnStr;
    }

    /**
     * 导出后台客户注册详情
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping({"/exportBorrowList"})
    public String exportBorrowList(HttpServletRequest request, Model model, @RequestParam(value = "userId", required = false) Integer userId,
                                   @RequestParam(value = "userName", required = false) String userName,
                                   @RequestParam(value = "borrowType", required = false) Integer borrowType,
                                   @RequestParam(value = "borrowId", required = false) String borrowId,
                                   @RequestParam(value = "status", required = false) Integer status,
                                   @RequestParam(value = "begin_date", required = false) String begin_date,
                                   @RequestParam(value = "end_date", required = false) String end_date) {

        PageBean page = new PageBean();
        page.setPageSize(null);
        List<Map<String, Object>> borrows = loanProvider.findPager(borrowId, userName, userId, borrowType, status, null, null, null, null, null, null, null, begin_date, end_date, page);
        for (Map<String, Object> map : borrows) {
            Object account = map.get("account");
            if (account != null) {
                map.put("account", account.toString());
            }
            String addtime = (String) map.get("addtime");
            if (addtime != null) {
                map.put("addtime", MsDateUtils.TimeStamp2DateTime(addtime));
            }

            String verify_time3 = (String) map.get("first_verify_time");
            if (verify_time3 != null) {
                map.put("first_verify_time", MsDateUtils.TimeStamp2DateTime(verify_time3));
            }
            String verify_time4 = (String) map.get("full_verify_time");
            if (verify_time4 != null) {
                map.put("full_verify_time", MsDateUtils.TimeStamp2DateTime(verify_time4));
            }
            String success_time = (String) map.get("success_time");
            if (success_time != null) {
                map.put("success_time", MsDateUtils.TimeStamp2DateTime(success_time));
            }
            String finish_time = (String) map.get("finish_time");
            if (finish_time != null) {
                map.put("finish_time", MsDateUtils.TimeStamp2DateTime(finish_time));
            }
            Object apr = map.get("apr");
            if (apr != null) {
                map.put("apr", apr.toString() + "%");
            }
            Object time_limit = map.get("time_limit");
            if (time_limit != null) {
                String timeLimit = "";
                Integer isDay = (Integer) map.get("is_day");
                if (isDay != null && isDay == 1) {
                    timeLimit = time_limit.toString() + "天";
                } else {
                    timeLimit = time_limit.toString() + "个月";
                }
                map.put("time_limit", timeLimit);
            }
            Object valid_time = map.get("valid_time");
            if (valid_time != null) {
                map.put("valid_time", valid_time + "天");
            }
            String end_time1 = (String) map.get("end_time");
            if (end_time1 != null) {
                map.put("end_time", MsDateUtils.TimeStamp2DateTime(end_time1));
            }
            Object amount_invested = map.get("amount_invested");
            if (amount_invested != null) {
                map.put("amount_invested", amount_invested);
            }
            Object tender_times = map.get("tender_times");
            if (tender_times != null) {
                map.put("tender_times", tender_times + "次");
            }
            Object repayment_account = map.get("repayment_account");
            if (repayment_account != null) {
                map.put("repayment_account", repayment_account);
            }
            Object repayment_yesaccount = map.get("repayment_yesaccount");
            if (repayment_yesaccount != null) {
                map.put("repayment_yesaccount", repayment_yesaccount);
            }
            Object style = map.get("style");
            if (style != null) {
                map.put("style", dictionaryProvider.getDictValue("borrow_style", style + ""));
            }
            Object status1 = map.get("status");
            if (status1 != null) {
                map.put("status", dictionaryProvider.getDictValue("borrow_status", status1.toString()));
            }
        }
        ExcelData excelData = new ExcelData();
        String fileName = "";
        if (status != null) {
            // 根据不同的状态返回不同页面
            int address = status;
            if (address == 0) {

                fileName = "融资申请";
                excelData.setHeads(
                        new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "项目编号", "借款金额", "借款期限", "年化收益率", "申请时间"});
                excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id", "number_id",
                        "account", "time_limit", "apr", "addtime"});
            } else if (address == 3) {

                fileName = "招标中";
                excelData.setHeads(new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "项目名", "项目编号", "借款金额", "借款期限",
                        "年化收益率", "风险审核人", "风险审核时间", "风险审核备注", "发布时间", "招标期限", "到期时间", "已筹金额", "投标次数"});
                excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id", "name",
                        "number_id", "account", "time_limit", "apr", "first_verify_user", "first_verify_time", "first_verify_remark",
                        "first_verify_user", "valid_time", "end_time", "amount_invested", "tender_times"});
            } else if (address == 4) {

                fileName = "满标复审";
                excelData.setHeads(new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "项目名", "项目编号", "借款金额", "借款期限",
                        "年化收益率", "风险审核人", "风险审核时间", "风险审核备注", "满标时间"});
                excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id", "name",
                        "number_id", "account", "time_limit", "apr", "first_verify_user", "first_verify_time", "first_verify_remark",
                        "success_time"});
            } else if (address == 5) {

                fileName = "还款中";

                excelData.setHeads(new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "项目名", "项目编号", "借款金额", "借款期限",
                        "年化收益率", "满标审核人", "满标审核时间", "满标审核备注", "成立时间", "还款方式", "应还金额", "已还金额"});
                excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id", "name",
                        "number_id", "account", "time_limit", "apr", "full_verify_user", "full_verify_time", "full_verify_remark",
                        "full_verify_time", "style", "repayment_account", "repayment_yesaccount"});
            } else if (address == 6) {

                fileName = "已完结";
                excelData.setHeads(new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "项目名", "项目编号", "借款金额", "借款期限",
                        "年化收益率", "完结时间", "还款方式", "应还金额", "已还金额"});
                excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id", "name",
                        "number_id", "account", "time_limit", "apr", "finish_time", "style", "repayment_account",
                        "repayment_yesaccount"});
            } else if (address == -1) {

                fileName = "已失败";
                excelData.setHeads(new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "项目编号", "借款金额", "借款期限", "年化收益率",
                        "申请时间", "项目状态"});
                excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id", "number_id",
                        "account", "time_limit", "apr", "addtime", "status"});
            }
        } else {

            fileName = "所有借款标";
            excelData.setHeads(
                    new String[]{"项目类型", "用户ID", "用户名称", "项目ID", "借款金额", "借款期限", "年化收益率", "申请时间", "项目状态"});
            excelData.setFieldNames(new String[]{"category_name", "user_id", "u_user_name", "id",
                    "account", "time_limit", "apr", "addtime", "status"});
        }
        excelData.setDataList(borrows);
        excelData.setModelClass(Map.class);
        model.addAttribute("excelData", excelData);
        model.addAttribute("fileName", fileName);
        return "excel";
    }

    /**
     * 到审核页面
     */
    @RequestMapping({"/toVerify"})
    public String toVerify(String borrowId, Model model) {

        if (StringUtils.isNotBlank(borrowId)) {
            Loan borrow = loanProvider.findById(borrowId);
            model.addAttribute("borrow", borrow);
        }
        return "admin/borrow/verify/review/input";
    }


    /**
     * 审核
     */
    @RequestMapping("/verify")
    @ResponseBody
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "borrowId", message = "⌚标的id不能为空"),
            @RequiredStringValidator(fieldName = "remark", message = "审核备注不能为空"),
            @RequiredStringValidator(fieldName = "token", message = "请不要重新提交，请刷新页面!")
    }, token = {
            @TokenValidator
    }
    )
    public Message verify(
            @RequestParam(value = "status", required = false) String status
            , @RequestParam(value = "remark", required = false) String remark
            , @RequestParam(value = "borrowId", required = false) String borrowId) {
        AdminUser emp = getCurrentEmp();
        Loan borrow = loanProvider.findById(borrowId);
        loanProvider.verify(borrow, status, emp, remark, AppContext.getRemoteIp());
        return Message.success("审核成功");
    }

    @RequestMapping("/full_cancel")
    @ResponseBody
    public Message full_cancel(@RequestParam(value = "borrowId", required = false) String borrowId) {
        AdminUser emp = getCurrentEmp();
        Loan loan = loanProvider.findById(borrowId);

        if(loan==null){
            throw  new NoticeException("借款标不存在");
        }
        loanProvider.full_cancel(loan, emp,AppContext.getRemoteIp());
        return Message.success("撤销成功");
    }

    @RequestMapping("/loan_cancel")
    @ResponseBody
    public Message loan_cancel( String LoanId) {
        AdminUser emp = getCurrentEmp();
        Loan loan = loanProvider.findById(LoanId);
        if(loan==null){
            throw  new NoticeException("借款标不存在");
        }
        loanProvider.loan_cancel(loan, emp,AppContext.getRemoteIp());
        return Message.success("撤销成功");
    }

    /**
     * 查看标的详细信息
     *
     * @param request
     * @return
     */
    @RequestMapping({"/input/{id}"})
    public String showBorrowDetail(HttpServletRequest request, @PathVariable String id) {
        Loan borrow = loanProvider.findById(id);
        List<LoanImg> borrowImgs = loanProvider.findImgByBorrowId(Integer.valueOf(id));
        request.setAttribute("borrow", borrow);
        request.setAttribute("borrowImgs", borrowImgs);
        List<LoanCategory> borrowTypes = loanCategoryProvider.findAll();
        request.setAttribute("borrowTypes", borrowTypes);
        return "admin/borrow/verify/apply/input";

    }

    /**
     * 发布标的
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "borrowId", message = "标Id不能为空"),
            @RequiredStringValidator(fieldName = "type", message = "标种类不能为空"),
            @RequiredStringValidator(fieldName = "name", message = "标名空"),
            @RequiredStringValidator(fieldName = "min_account", message = "最低金额不能为空"),
            @RequiredStringValidator(fieldName = "max_account", message = "最大金额不能为空"),
            @RequiredStringValidator(fieldName = "apr", message = "利率不能为空"),
            @RequiredStringValidator(fieldName = "time_limit", message = "还款期限不能为空"),
            @RequiredStringValidator(fieldName = "valid_time", message = "融资期限不能为空"),
            @RequiredStringValidator(fieldName = "account", message = "金额不能为空")
    })
    @RequestMapping(value = {"/publish"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Message publish(HttpServletRequest request, HttpSession session
            , @RequestParam(value = "borrowId", required = false) String id
            , @RequestParam(value = "name", required = false) String name
            , @RequestParam(value = "password", required = false) String password
            , @RequestParam(value = "account", required = false) String account
            , @RequestParam(value = "apr", required = false) String apr
            , @RequestParam(value = "time_limit", required = false) Integer time_limit
            , @RequestParam(value = "min_account", required = false, defaultValue = "0") String min_account
            , @RequestParam(value = "max_account", required = false, defaultValue = "0") String max_account
            , @RequestParam(value = "is_day", required = false) Integer is_day
            , @RequestParam(value = "style", required = false) Integer style
            , @RequestParam(value = "valid_time", required = false) Integer valid_time
            , @RequestParam(value = "radio_account", required = false, defaultValue = "0") String radio_account
            , @RequestParam(value = "red_packet_status", required = false, defaultValue = "0") Integer red_packet_status
            , @RequestParam(value = "auto_status", required = false, defaultValue = "0") Integer auto_status
            , @RequestParam(value = "nd_verify_time", required = false) String nd_verify_time

            , @RequestParam(value = "content", required = false) String content


    ) {
        AdminUser emp = getCurrentEmp();
        Loan loan = loanProvider.findById(id);
        if(loan  == null){
           return  Message.error("借款标不存在");
        }

        if(loan.getStatus() != null && loan.getStatus() >= 3){
            return  Message.error("借款标已发布，请不要重复提交！");
        }

        //天标还款方式必须是一次性还本付息
        if(1 == is_day && !LoanRepayStyle.STYLE_0.getValue().equals(style)){
            return Message.error("天标还款方式必须是"+ LoanRepayStyle.STYLE_0.getName());
        }


        //秒标只能发月标
        if(1==is_day && LoanType.TYPE_10.getValue().equals(loan.getLoan_category())){
            return Message.error(LoanType.TYPE_10.getName()+"只能发月标!请您核对一下");
        }

        loan.setName(name);
        loan.setLoan_category(Integer.parseInt(request.getParameter("type")));
        if (8 == loan.getLoan_category()) {
            loan.setPassword(password);
        }
        loan.setAccount(new BigDecimal(account));
        loan.setApr(new BigDecimal(apr));
        loan.setTime_limit(time_limit);
        loan.setIs_day(is_day);
        loan.setPay_style(style + "");
        loan.setMin_account(new BigDecimal(min_account));
        loan.setMax_account(new BigDecimal(max_account));
        loan.setAmount_invested(new BigDecimal(0));
        loan.setValid_time(valid_time);
        loan.setRadio_account(new BigDecimal(radio_account));
        loan.setUse("借款");
        loan.setContent(content);
        loan.setRed_packet_status(red_packet_status);
        loan.setRepayment_periods(loan.getPay_style().equals("0") ? 1 : loan.getTime_limit());
        AmountUtil.cacueInterest(loan);
        String[] borrowImgs = request.getParameterValues("borrowImgs");
        if (borrowImgs != null) {
            loanProvider.delImgByBorrowId(loan.getId());
            for (int i = 0; i < borrowImgs.length; i++) {
                LoanImg img = new LoanImg();
                img.setBorrow_id(loan.getId());
                img.setImg(borrowImgs[i]);
                loanProvider.insertImg(img);
            }
        }


        loan.setFirst_verify_user(emp.getName());
        loan.setFirst_verify_time(MsDateUtils.getTime());
        loan.setFirst_verify_remark("发标");

        loan.setEnd_time(MsDateUtils.getDayTime(loan.getValid_time()));
        loan.setStatus(3);
        if(auto_status==1){
            if(StringUtils.isBlank(nd_verify_time)){
                throw  new NoticeException("预约标请输入预约时间");
            }

            loan.setFirst_verify_remark("发标");
            loan.setFirst_verify_time(MsDateUtils.dateTime2TimeStamp(nd_verify_time));
            loan.setStatus(2);
            loan.setIs_auto(auto_status);
            loan.setNd_verify_time(MsDateUtils.dateTime2TimeStamp(nd_verify_time));

        }

        loanProvider.update(loan);
        return Message.success("发布成功");
    }

    /**
     * 编辑标的
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "borrowId", message = "标Id不能为空"),
            @RequiredStringValidator(fieldName = "type", message = "标种类不能为空"),
            @RequiredStringValidator(fieldName = "name", message = "标名空"),
            @RequiredStringValidator(fieldName = "min_account", message = "最低金额不能为空"),
            @RequiredStringValidator(fieldName = "max_account", message = "最大金额不能为空"),
            @RequiredStringValidator(fieldName = "apr", message = "利率不能为空"),
            @RequiredStringValidator(fieldName = "time_limit", message = "还款期限不能为空"),
            @RequiredStringValidator(fieldName = "valid_time", message = "融资期限不能为空"),
            @RequiredStringValidator(fieldName = "account", message = "金额不能为空")
    })
    @RequestMapping(value = {"/save"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Message save(HttpServletRequest request, HttpSession session
            , @RequestParam(value = "borrowId", required = false) String id
            , @RequestParam(value = "name", required = false) String name
            , @RequestParam(value = "password", required = false) String password
            , @RequestParam(value = "account", required = false) String account
            , @RequestParam(value = "apr", required = false) String apr
            , @RequestParam(value = "time_limit", required = false) Integer time_limit
            , @RequestParam(value = "min_account", required = false, defaultValue = "0") String min_account
            , @RequestParam(value = "max_account", required = false, defaultValue = "0") String max_account
            , @RequestParam(value = "is_day", required = false) Integer is_day
            , @RequestParam(value = "style", required = false) Integer style
            , @RequestParam(value = "valid_time", required = false) Integer valid_time
            , @RequestParam(value = "radio_account", required = false, defaultValue = "0") String radio_account
            , @RequestParam(value = "content", required = false) String content
    ) {
        AdminUser emp = getCurrentEmp();
        Loan loan = loanProvider.findById(id);

        if(loan  == null){
            return  Message.error("借款标不存在");
        }

        if(loan.getStatus() != null && loan.getStatus() >= 3){
            return  Message.error("借款标已发布，请不要重复提交！");
        }

        //天标还款方式必须是一次性还本付息
        if(1 == is_day && !LoanRepayStyle.STYLE_0.getValue().equals(style)){
            return Message.error("天标还款方式必须是"+ LoanRepayStyle.STYLE_0.getName());
        }

        //秒标只能发月标
        if(1==is_day && LoanType.TYPE_10.getValue().equals(loan.getLoan_category())){
            return Message.error(LoanType.TYPE_10.getName()+"只能发月标!请您核对一下");
        }

        loan.setName(name);
        loan.setLoan_category(Integer.parseInt(request.getParameter("type")));
        if (8 == loan.getLoan_category()) {
            loan.setPassword(password);
        }
        loan.setAccount(new BigDecimal(account));
        loan.setApr(new BigDecimal(apr));
        loan.setTime_limit(time_limit);
        loan.setIs_day(is_day);
        loan.setPay_style(style + "");
        loan.setMin_account(new BigDecimal(min_account));
        loan.setMax_account(new BigDecimal(max_account));
        loan.setAmount_invested(new BigDecimal(0));
        loan.setValid_time(valid_time);
        loan.setRadio_account(new BigDecimal(radio_account));
        loan.setUse("借款");
        loan.setContent(content);
        loan.setRepayment_periods(loan.getPay_style().equals("0") ? 1 : loan.getTime_limit());
        AmountUtil.cacueInterest(loan);
        String[] borrowImgs = request.getParameterValues("borrowImgs");
        if (borrowImgs != null) {
            loanProvider.delImgByBorrowId(loan.getId());
            for (int i = 0; i < borrowImgs.length; i++) {
                LoanImg img = new LoanImg();
                img.setBorrow_id(loan.getId());
                img.setImg(borrowImgs[i]);
                loanProvider.insertImg(img);
            }
        }

        loanProvider.update(loan);
        return Message.success("保存成功");
    }


    @Override
    public boolean getBinderFlag() {
        return false;
    }
}
